package com.stx.handler;

public class MessageQueue {

    private final boolean mQuitAllowed;

    public Message mMessages;
    private boolean mQuitting;
    private boolean mBlocked = true;
    private int mNextBarrierToken;
    private final Object lockObj;

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        lockObj = new Object();
    }

    /**
     * 将消息放置到消息队列中，注意线程同步
     * 将消息插入到队列的尾部
     * @param msg
     * @param when
     * @return
     */
    public  boolean enqueueMessage(Message msg, long when){

        if (msg.target == null){
            throw new IllegalArgumentException("msg.target is null...");
        }
        if (msg.isInUse()){
            throw new IllegalStateException("msg is in used...");
        }
        synchronized (this){
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                System.out.println(e);
                msg.recycle();
                return false;
            }
            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p;
                prev.next = msg;
            }
            // We can assume mPtr != 0 because mQuitting is false.
            needWake = true;  //没有去判断是否空闲, 强行设置为true
            if (needWake) {
                synchronized (lockObj) {
                    lockObj.notify();
                }
            }
        }
        return false;
    }

    /**
     * 移除所有消息
     * @param h
     * @param object
     */
    public void removeCallbacksAndMessages(Handler h, Object object){
        if (h == null) {
            return;
        }
        synchronized (this) {
            Message p = mMessages;
            // Remove all messages at front.
            while (p != null && p.target == h
                    && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }
            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

    boolean hasMessages(Handler h) {
        if (h == null) {
            return false;
        }

        synchronized (this) {
            Message p = mMessages;
            while (p != null) {
                if (p.target == h) {
                    return true;
                }
                p = p.next;
            }
            return false;
        }
    }

    boolean hasMessages(Handler h, int what, Object object) {
        if (h == null) {
            return false;
        }
        synchronized (this) {
            Message p = mMessages;
            while (p != null) {
                if (p.target == h && p.what == what && (object == null || p.obj == object)) {
                    return true;
                }
                p = p.next;
            }
            return false;
        }
    }

    /**
     * 从队列中移除消息
     * @param h
     * @param what
     * @param object
     */
    void removeMessages(Handler h, int what, Object object) {
        if (h == null) {
            return;
        }
        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h && p.what == what
                    && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }

            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && n.what == what
                            && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

    public void quit(boolean safe){
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }
        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            synchronized (lockObj) {
                lockObj.notify();
            }
        }
    }

    public Message next(){
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {

            synchronized (lockObj) {
                try {
                    lockObj.wait(nextPollTimeoutMillis);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = System.currentTimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
//                if (pendingIdleHandlerCount < 0
//                        && (mMessages == null || now < mMessages.when)) {
//                    pendingIdleHandlerCount = mIdleHandlers.size();
//                }
//                if (pendingIdleHandlerCount <= 0) {
//                    // No idle handlers to run.  Loop and wait some more.
//                    mBlocked = true;
//                    continue;
//                }

//                if (mPendingIdleHandlers == null) {
//                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
//                }
//                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);

            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
//            for (int i = 0; i < pendingIdleHandlerCount; i++) {
//                final IdleHandler idler = mPendingIdleHandlers[i];
//                mPendingIdleHandlers[i] = null; // release the reference to the handler
//
//                boolean keep = false;
//                try {
//                    keep = idler.queueIdle();
//                } catch (Throwable t) {
//                    Log.wtf(TAG, "IdleHandler threw exception", t);
//                }
//
//                if (!keep) {
//                    synchronized (this) {
//                        mIdleHandlers.remove(idler);
//                    }
//                }
//            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

    public boolean isIdle() {
        synchronized (this) {
            final long now = System.currentTimeMillis();
            return mMessages == null || now < mMessages.when;
        }
    }


    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

    private void removeAllFutureMessagesLocked() {
        final long now = System.currentTimeMillis();
        Message p = mMessages;
        if (p != null) {
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }


}



